package com.wzl.swzl.controller;

import com.wzl.swzl.controller.Result.Code;
import com.wzl.swzl.controller.Result.Msg;
import com.wzl.swzl.controller.Result.Result;
import com.wzl.swzl.entity.User;
import com.wzl.swzl.service.UserService;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wzl
 * @version 1.0
 * @intro:
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     *
     * @param user
     * @param checkCode
     * @param session
     * @param model
     * @param view
     * @return
     */
    @PostMapping("/login")
    public ModelAndView login(User user, String checkCode, HttpSession session, Model model, ModelAndView view) {
        Object sessionCode = session.getAttribute("sessionCode");
        if (!checkCode.equals(sessionCode)) {
            model.addAttribute("errorMsg", "验证码错误");
//            return "login";
            view.setViewName("login");
            return view;
        }
        String authority = user.getAuthority();
        if ("用户".equals(authority)) {
            User dbUser = userService.findByUsername(user.getUsername());
            if (null != dbUser && user.getPassword().equals(dbUser.getPassword())) {
                session.setAttribute("loginUser", dbUser);
                view.setView(new RedirectView("/swzl/index", false));
                return view;
//            return "/index";
//                return "redirect:index";
            } else {
                model.addAttribute("errorMsg", "用户名或密码错误");
//                return "login";
                view.setViewName("login");
                return view;
            }
        } else {
            User dbUser = userService.findByUsername(user.getUsername());
            if (null != dbUser && user.getPassword().equals(dbUser.getPassword()) && dbUser.getAuthority().contains("管理员")) {
                session.setAttribute("loginUser", dbUser);
//            return "/index";
//                return "redirect:houTaiIndex";
                view.setViewName("admin/houTaiIndex");
                return view;
            } else {
                model.addAttribute("errorMsg", "用户名或密码错误");
//                return "login";
                view.setViewName("login");
                return view;
            }
        }
    }


    //ajax验证用户名称是否可用username
    @RequestMapping("/checkName")
    @ResponseBody//返回json数据到前端
    public boolean ajaxCheckName(String username) {
        username = username.trim();
        if (StringUtils.isEmpty(username) || username.length() == 0 || username.length() > 10) {
            return false;
        }
        User resCheckNameUser = userService.findByUsername(username);
        return null == resCheckNameUser;
    }


    //ajax返回注册信息
    @RequestMapping("/register")
    @ResponseBody//返回字符串数据到前端
    public String ajaxCheckRegister(@RequestBody User user) {
        String username = user.getUsername().trim();
        String password = user.getPassword().trim();
        if (username.equals("")) {
            return "注册失败，用户名为空！";
        }
        if (password.equals("")) {
            return "注册失败，密码为空！";
        }
        User resCheckRegister = userService.findByUsername(user.getUsername());
        if (resCheckRegister != null && resCheckRegister.getUsername().equals(user.getUsername())) {
            return "注册失败，该用户已存在！";
        } else {
            Date date = new Date();
            if (user.getSex().equals("M")) {
                user.setSex("男");
            } else {
                user.setSex("女");
            }
            user.setAuthority("普通用户");
            user.setAddtime(date);
            userService.add(user);
//            Integer id = user.getId();
            return "注册成功！";
        }
    }

    //注销登录
    @GetMapping("/logout")
    @ResponseBody
    public Result logout(HttpServletRequest request) {

        try {
            HttpSession session = request.getSession();
            session.invalidate();
            Map<String,String> map = new HashMap<>();
            map.put("status","200");
            map.put("result","session清空！");
/*
            String res = "{\"status\":\"200\",\"result\":\"session清空！\"}";
            JSONObject json = new JSONObject(res);*/
            return new Result(Code.LOGOUT_OK,map, Msg.LOGOUT_OK);
        } catch (JSONException e) {
            e.printStackTrace();
            return new Result(Code.LOGOUT_ERR, Msg.LOGOUT_ERR);
        }
    }

    //后台超级管理员获取普通用户列表信息
    @RequestMapping("/HTUserList")
    @ResponseBody//返回字符串数据到前端
    public Result HTUserList(@RequestBody User user) {
        Integer userid = user.getId();
        User dbUser = userService.findByUserId(userid);
        if (null == dbUser || !"超级管理员".equals(dbUser.getAuthority())) {
            return new Result(Code.POST_ERR, Msg.QUERY_ERR);
        } else {
            List<User> userEntitys = userService.findAllUser();
            if (userEntitys.size() > 0) {
                Map<String,Object> map = new HashMap<>();
                map.put("status","true");
                map.put("data",userEntitys);
                return new Result(Code.POST_OK,map,Msg.QUERY_OK);
            } else {
                return new Result(Code.POST_ERR, Msg.QUERY_ERR);
            }
        }
    }

    //后台超级管理员获取普通管理员用户列表信息
    @RequestMapping("/HTUserGLList")
    @ResponseBody//返回字符串数据到前端
    public Result HTUserGLList(@RequestBody User user) {
        Integer userid = user.getId();
        User dbUser = userService.findByUserId(userid);
        if (null == dbUser || !"超级管理员".equals(dbUser.getAuthority())) {
            return new Result(Code.POST_ERR, Msg.QUERY_ERR);
        } else {
            List<User> userEntitys = userService.findAllGLUser();
            if (userEntitys.size() > 0) {
                Map<String,Object> map = new HashMap<>();
                map.put("status","true");
                map.put("data",userEntitys);
                return new Result(Code.POST_OK,map,Msg.QUERY_OK);
            } else {
                return new Result(Code.POST_ERR, Msg.QUERY_ERR);
            }
        }
    }

    //超级管理员修改用户权限为管理员
    @GetMapping("/HTGLUser")
    public String HTGLUser(String id) {
        if ("".equals(id) || id.length() == 0) {
            return "false";
        }
        userService.updateGL(id);
        return "redirect:houTaiUser";
    }

    //超级管理员修改用户权限为普通用户
    @GetMapping("/HTQXUser")
    public String HTQXUser(String id) {
        if ("".equals(id) || id.length() == 0) {
            return "false";
        }
        userService.updateQX(id);
        return "redirect:houTaiUser";
    }

    //超级管理员删除用户
    @GetMapping("/HTUserDelete")
    public String HTUserDelete(String id) {
        if ("".equals(id) || id.length() == 0) {
            return "false";
        }
        userService.delete(id);
        return "redirect:houTaiUser";
    }


}
